package cn.tedu.straw.portal.security;

import cn.tedu.straw.portal.service.IUserService;
import cn.tedu.straw.portal.vo.UserLoginVO;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private IUserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if(username==null){
            return null;
        }
        UserLoginVO user=userService.getLoginUserInfo(username);
        if(user==null){
            return null;
        }
//        String[] authorities = new String[user.getPermissions().size()];
//        for (int i=0;i<authorities.length;i++){
//            authorities[i] = user.getPermissions().get(i).getAuthority();
//        }
        List<SimpleGrantedAuthority> authorities=new ArrayList<>();
      for (int i=0;i<user.getPermissions().size();i++){
        String authority =  user.getPermissions().get(i).getAuthority();
        SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(authority);
        authorities.add(simpleGrantedAuthority);
      }

//        UserDetails userDetails = User.builder().username(user.getPhone())
//                .password(user.getPassword())
//                .accountLocked(user.getIsLocked()==1)
//                .disabled(user.getIsEnabled()==0)
//                .authorities(authorities)
//                .build();

        LoginUserInfo loginUserInfo=new LoginUserInfo(user.getPhone(),user.getPassword(),
                user.getIsLocked()==0,true,true,user.getIsEnabled()==1,
               authorities);
        loginUserInfo.setId(user.getId());
        loginUserInfo.setNickName(user.getNickName());
        loginUserInfo.setPhone(user.getPhone());
        loginUserInfo.setAccountType(user.getAccountType());
        return loginUserInfo;
    }
}
